package com.bd.module.salegood.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import com.bd.framework.utils.UtilsTool;
import com.bd.framework.utils.SystTimeUpdateTimer;
import com.bd.module.BaseFrame;
import com.bd.module.salegood.pojo.GoodsDataModel;
import com.bd.module.salegood.server.impl.SaleGoodServiceImpl;

import conf.MyScrollBar;

public class SalseGoodPanel extends JPanel implements ActionListener{
	private static final long serialVersionUID = 5862381991938898841L;
	protected static final String ORDERNUMBER_FILE = "OrderNumberFile";
	public static int orderNumber;							  //商品流水帐号
	public static boolean isAddOrderNumber;					  //商品交易流水帐号是否加1判断；
	private SaleGoodServiceImpl sgsi = new SaleGoodServiceImpl();
	static private SalseGoodPanel sgp;
	public static SalseGoodPanel getSgp(){
		if(sgp==null){sgp=new SalseGoodPanel();}
		return sgp;
	}
	public void setFoucs(){
		goodsCodeField.requestFocus();
    }
	/**
	 * 初始化table窗格，此时窗格中的数据为空
	 */
	private void initTable(){
		table.setModel(sgsi.getDataModel());       
	}
	public JTextField goodsCodeField;
	private JTextField alterNumTF;
	private JTextField textField_5;
	private JNumberOnlyField payMoneyLb;
	private JTextField textField_7;
	private JTextField textField_8;
	private JTextField textField_14;
	private JTextField textField_15;
	private JTextField textField_16;
	private JTextField textField_17;
	private JTextField textField_18;
	private JTextField textField_19;
	private JTable table;
	private JLabel TotalMoneyLb;
	private JLabel GoodNameLb;
	private JScrollPane saleScrollPane;
	private int isNeedBottom = 0;
	Rectangle rect;
	/**pcTimeTxtF,销售界面的当前本机时间*/
	private JLabel pcTimelb;
	/**获得当前屏幕分辨率宽度*/
	private 	double width = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
	/**获得当前屏幕分辨率高度*/
	private double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
	private JPanel collectPanel;
public SalseGoodPanel(){
	this.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "\u9500\u552E", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));
	
	this.setLayout(null);
	try{										 //初始化当前的流水帐号
		DataInputStream readData = new DataInputStream(new FileInputStream(ORDERNUMBER_FILE));
		orderNumber = readData.readInt();
		readData.close();
	}
	catch(IOException io){
		orderNumber = 1;                         //初始化流水帐号文件丢失，将流水号置1；
		System.out.println(io.getMessage());
	}
	
	//JTable的数据(销售界面)
	table = new JTable();
	int  rowCount = table.getRowCount();   
	table.getSelectionModel().setSelectionInterval(rowCount-1 , rowCount- 1 );   
	rect = table.getCellRect(rowCount-1 ,  0 ,  true );   
	initTable();
	
	goodsCodeField = new JTextField();
	goodsCodeField.addKeyListener(new KeyAdapter() {
		@Override
		public void keyPressed(KeyEvent keyEvent) {
			//每次输入完成需要点击Enter键,驱动光标转移
			if(keyEvent.getKeyCode() == KeyEvent.VK_ENTER){
				String goodcode=goodsCodeField.getText();
				sgsi.productData(goodcode);
				GoodNameLb.setText("商品名称： "+sgsi.getDataModel().getGoodsName());
				TotalMoneyLb.setText(sgsi.getMoneyString());
				
				int rowCount = table.getRowCount();
				table.getSelectionModel().setSelectionInterval(rowCount-1, rowCount-1);
				Rectangle rect = table.getCellRect(rowCount-1, 0, true);
				
				table.revalidate (); // 可以不要
				table.repaint();                        //重画窗口，可以不要
				table.scrollRectToVisible(rect);
				
				goodsCodeField.setText("");
			}  
			if(keyEvent.getKeyCode() == KeyEvent.VK_UP){
				int selectRow = table.getSelectedRow();
				//table.setFocusable(true);
				System.out.println("选中行数："+selectRow);
				table.getSelectionModel().setSelectionInterval(selectRow-1, selectRow-1);
				Rectangle rect = table.getCellRect(selectRow-1, 0, true);
				
				table.revalidate (); // 可以不要
				table.repaint();                        //重画窗口，可以不要
				table.scrollRectToVisible(rect);
			}
			if(keyEvent.getKeyCode() == KeyEvent.VK_DOWN){
				int selectRow = table.getSelectedRow();
				System.out.println("向下翻页选中行数:"+selectRow+"总行数:"+table.getRowCount());
				//table.setFocusable(true);
				if((selectRow+2) >= table.getRowCount()){
					selectRow =  table.getRowCount()-2;
				}
				table.getSelectionModel().setSelectionInterval(selectRow+1, selectRow+1);
				Rectangle rect = table.getCellRect(selectRow+1, 0, true);
				
				table.revalidate (); // 可以不要
				table.repaint();                        //重画窗口，可以不要
				table.scrollRectToVisible(rect);
			}
			//执行delete 删除jtable 选中行
			if(keyEvent.getKeyCode() == KeyEvent.VK_F4){
				int selectRow = table.getSelectedRow();
				//table.setFocusable(true);
				System.out.println("删除的选中行数："+selectRow);
				GoodsDataModel tm = (GoodsDataModel)table.getModel();
				tm.removeLastVector(selectRow);
			}
		}
	});
	goodsCodeField.setBounds(75, 614, 66, 21);
	this.add(goodsCodeField);
	goodsCodeField.setColumns(10);
	
	saleScrollPane = new JScrollPane(table);
	table.setRowHeight(40);
	table.setFont(new Font("",Font.BOLD,20));
	/**
	 * 暂定整个销售界面的高度比例3:1,及销售商品信息的ScrollPane占高度的3份
	 * 宽度比位4:1,及销售商品信息的ScrollPane占高度的4份
	 * */
	saleScrollPane.setBounds(10, 20, 971, 580);
	this.add(saleScrollPane);
	
	collectPanel = new JPanel();
	collectPanel.setToolTipText("收款信息");
	collectPanel.setBorder(new TitledBorder(null, "\u6536\u6B3E\u4FE1\u606F", TitledBorder.LEADING, TitledBorder.TOP, null, null));
	collectPanel.setBounds(1061, 48, 199, 125);
	this.add(collectPanel);
	collectPanel.setLayout(null);
	
	JLabel label = new JLabel("金 额：");
	label.setFont(new Font("楷体", Font.PLAIN, 20));
	label.setBounds(10, 27, 70, 21);
	collectPanel.add(label);
	
	JLabel label_18 = new JLabel("实 收：");
	label_18.setFont(new Font("楷体", Font.PLAIN, 20));
	label_18.setBounds(10, 58, 70, 21);
	collectPanel.add(label_18);
	
	JLabel label_19 = new JLabel("应 找：");
	label_19.setFont(new Font("楷体", Font.PLAIN, 20));
	label_19.setBounds(10, 89, 70, 21);
	collectPanel.add(label_19);
	
	TotalMoneyLb = new JLabel("0.0");
	TotalMoneyLb.setFont(new Font("楷体", Font.PLAIN, 20));
	TotalMoneyLb.setBounds(94, 32, 95, 15);
	collectPanel.add(TotalMoneyLb);
	
	final JLabel lblNewLabel_6 = new JLabel("0.0");
	lblNewLabel_6.setFont(new Font("楷体", Font.PLAIN, 20));
	lblNewLabel_6.setBounds(94, 63, 95, 15);
	collectPanel.add(lblNewLabel_6);
	
	final JLabel lblNewLabel_7 = new JLabel("0.0");
	lblNewLabel_7.setFont(new Font("楷体", Font.PLAIN, 20));
	lblNewLabel_7.setBounds(94, 94, 95, 15);
	collectPanel.add(lblNewLabel_7);
	
	JPanel curentPanel = new JPanel();
	curentPanel.setBorder(new TitledBorder(null, "\u5F53\u524D\u4FE1\u606F", TitledBorder.LEADING, TitledBorder.TOP, null, null));
	curentPanel.setBounds(1061, 196, 199, 115);
	this.add(curentPanel);
	
	JLabel lblNewLabel = new JLabel("当前笔数");
	curentPanel.add(lblNewLabel);
	curentPanel.setLayout(null);
	
	JLabel lblNewLabel_1 = new JLabel("当前笔数：");
	lblNewLabel_1.setFont(new Font("楷体", Font.PLAIN, 20));
	lblNewLabel_1.setBounds(10, 26, 118, 18);
	curentPanel.add(lblNewLabel_1);
	
	JLabel label_20 = new JLabel("总笔数：");
	label_20.setFont(new Font("楷体", Font.PLAIN, 20));
	label_20.setBounds(10, 54, 94, 30);
	curentPanel.add(label_20);
	
	textField_14 = new JTextField();
	textField_14.setEditable(false);
	textField_14.setBounds(87, 26, 17, 0);
	curentPanel.add(textField_14);
	textField_14.setColumns(10);
	
	textField_15 = new JTextField();
	textField_15.setEditable(false);
	textField_15.setBounds(97, 27, 79, 21);
	curentPanel.add(textField_15);
	textField_15.setColumns(10);
	
	textField_16 = new JTextField();
	textField_16.setEditable(false);
	textField_16.setBounds(99, 61, 77, 21);
	curentPanel.add(textField_16);
	textField_16.setColumns(10);
	
	JPanel discountPanle = new JPanel();
	discountPanle.setToolTipText("挂单信息");
	discountPanle.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "\u6302\u5355\u4FE1\u606F", TitledBorder.LEADING, TitledBorder.TOP, null, null));
	discountPanle.setBounds(1061, 339, 199, 83);
	discountPanle.setLayout(null);
	this.add(discountPanle);
	
	JLabel lblNewLabel_2 = new JLabel("金 额：");
	lblNewLabel_2.setFont(new Font("楷体", Font.PLAIN, 20));
	lblNewLabel_2.setBounds(10, 37, 92, 18);
	discountPanle.add(lblNewLabel_2);
	
	textField_17 = new JTextField();
	textField_17.setEditable(false);
	textField_17.setBounds(99, 38, 78, 21);
	discountPanle.add(textField_17);
	textField_17.setColumns(10);
	
	JPanel memberPanel = new JPanel();
	memberPanel.setBorder(new TitledBorder(null, "\u4F1A\u5458\u4FE1\u606F", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
	memberPanel.setBounds(1061, 460, 199, 125);
	memberPanel.setLayout(null);
	this.add(memberPanel);
	
	JLabel label_21 = new JLabel("卡 号：");
	label_21.setFont(new Font("楷体", Font.PLAIN, 20));
	label_21.setBounds(10, 32, 75, 21);
	memberPanel.add(label_21);
	
	JLabel label_22 = new JLabel("会员星级：");
	label_22.setFont(new Font("楷体", Font.PLAIN, 20));
	label_22.setBounds(10, 77, 114, 18);
	memberPanel.add(label_22);
	
	textField_18 = new JTextField();
	textField_18.setEditable(false);
	textField_18.setBounds(105, 20, 75, 21);
	memberPanel.add(textField_18);
	textField_18.setColumns(10);
	
	textField_19 = new JTextField();
	textField_19.setEditable(false);
	textField_19.setBounds(105, 77, 75, 21);
	memberPanel.add(textField_19);
	textField_19.setColumns(10);
	
	pcTimelb = new JLabel();
	pcTimelb.setFont(new Font("楷体", Font.PLAIN, 16));
	
	pcTimelb.setBounds(1051, 10, 244, 21);
	this.add(pcTimelb);
	
	pcTimelb.setText(UtilsTool.getDate("yyyy-MM-dd HH:mm:ss"));
	new	SystTimeUpdateTimer(pcTimelb);
	
	JLabel label_4 = new JLabel("代码:");
	label_4.setFont(new Font("楷体", Font.PLAIN, 20));
	label_4.setBounds(10, 607, 78, 31);
	this.add(label_4);
	
	JLabel label_5 = new JLabel("数量:");
	label_5.setFont(new Font("楷体", Font.PLAIN, 20));
	label_5.setBounds(167, 607, 54, 31);
	this.add(label_5);
	
	alterNumTF = new JTextField();
	alterNumTF.setBounds(224, 614, 78, 21);
	this.add(alterNumTF);
	alterNumTF.setColumns(10);
	alterNumTF.addKeyListener(new KeyAdapter() {
		@Override
		public void keyPressed(KeyEvent keyEvent) {
			System.out.println("执行否");
			//每次输入完成需要点击Enter键,驱动光标转移
			if(keyEvent.getKeyCode() == KeyEvent.VK_ENTER){
				String alterNum=alterNumTF.getText();
				int goodsNumber = Integer.parseInt(alterNum);
				sgsi.alterGoodsNum(goodsNumber);
				goodsCodeField.requestFocus();
				table.revalidate();
				table.repaint();
			}  
		}		
	});
	
	JLabel label_6 = new JLabel("折率:");
	label_6.setFont(new Font("楷体", Font.PLAIN, 20));
	label_6.setBounds(466, 612, 54, 21);
	this.add(label_6);
	
	textField_5 = new JTextField();
	textField_5.setBounds(564, 614, 87, 21);
	this.add(textField_5);
	textField_5.setColumns(10);
	
	JLabel label_7 = new JLabel("实收金额:");
	label_7.setFont(new Font("楷体", Font.PLAIN, 20));
	label_7.setBounds(678, 607, 124, 31);
	this.add(label_7);
	
	payMoneyLb = new JNumberOnlyField(14);
	payMoneyLb.setBounds(812, 614, 98, 21);
	this.add(payMoneyLb);
	payMoneyLb.setColumns(10);
	payMoneyLb.addKeyListener(new KeyAdapter() {
		@Override
		public void keyPressed(KeyEvent keyEvent) {
			
			//每次输入完成需要点击Enter键,驱动光标转移
			if(keyEvent.getKeyCode() == KeyEvent.VK_ENTER){
			String	payMoney = payMoneyLb.getText();
			double moneys = GoodsDataModel.getGoodsMoneys();
			double payMoneys = Double.parseDouble(payMoney);
			String returnMoneys = String.valueOf(Math.floor((payMoneys - moneys) * 100.0 + 0.5)/100.0);
			lblNewLabel_6.setText(payMoney);
			lblNewLabel_7.setText(returnMoneys);
			payMoneyLb.setText(" ");
			goodsCodeField.requestFocus();
			}   
		}		
	});

	JLabel label_8 = new JLabel("营业员:");
	label_8.setFont(new Font("楷体", Font.PLAIN, 20));
	label_8.setBounds(466, 648, 87, 28);
	this.add(label_8);
	
	textField_7 = new JTextField();
	textField_7.setBounds(564, 654, 87, 21);
	this.add(textField_7);
	textField_7.setColumns(10);
	
	JLabel label_9 = new JLabel("磁卡号:");
	label_9.setFont(new Font("楷体", Font.PLAIN, 20));
	label_9.setBounds(673, 648, 103, 28);
	this.add(label_9);
	
	textField_8 = new JTextField();
	textField_8.setBounds(812, 654, 98, 21);
	this.add(textField_8);
	textField_8.setColumns(10);
	
	 GoodNameLb = new JLabel("商品名称：");
	GoodNameLb.setFont(new Font("楷体", Font.PLAIN, 18));
	GoodNameLb.setBounds(10, 657, 423, 34);
	add(GoodNameLb);
	
	JLabel lblNewLabel_4 = new JLabel("规格：");
	lblNewLabel_4.setFont(new Font("华文楷体", Font.PLAIN, 18));
	lblNewLabel_4.setBounds(10, 701, 244, 15);
	add(lblNewLabel_4);
	
	JLabel lblNewLabel_5 = new JLabel("单位：");
	lblNewLabel_5.setFont(new Font("楷体", Font.PLAIN, 18));
	lblNewLabel_5.setBounds(304, 689, 54, 15);
	add(lblNewLabel_5);
	this.addKeyListener( new KeyMonitor());

}
/**
 * 对话框的监听方法的实现，此监听是在SalseGoodPanel中添加的
 * F1: 销售挂单（挂起当前的商品交易）
 * F2: 开钱箱（触发硬件指令方法打开钱箱）
 * F3: 全部删除
 * F4: 单行删除
 * F5: 修改数量
 * F6: 付款（当对话框结束后此方法还将清空） 
 * F7: 刷会员卡
 * F8: 打折
 * F9: 修改零售价
 * F11: 挂机
 * SHIFT+F2: 补打
 * ESC : 退出
 * F12 : 银联签到 
 * SHIFT+F3: 联票号输入
 * F1：当对话框结束后此方法还将清空table中的数据并等待下次交易
 * F4：可以清除最后一笔的商品交易信息
 * F5：挂起当前的商品交易
 * F6: 调出当前挂起交易的信息并进行相应的处理
 * Esc：退出系统
 */
private class KeyMonitor extends KeyAdapter{
	public void keyReleased(KeyEvent keyEvent) {
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F1) {
			if(GoodsDataModel.checkVector()){
				JOptionPane.showMessageDialog(null,"没有交易的商品，无需挂起交易");
			}
			else{
				pauseExchange();//挂起交易
			}
    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_D && keyEvent.isAltDown()){
			if(MyListDataModel.checkListVector()){
				JOptionPane.showMessageDialog(null,"没有挂起的交易");
			}
			else{
				managerExchange();//返回交易
			}
		}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F4) {
			if(GoodsDataModel.checkVector()){
				JOptionPane.showMessageDialog(null,"没有交易的商品，无需删除");
			}
			else{
				//清楚选中的商品信息
				clearGoods(table.getSelectedRow());//清涂商品
			}
    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F5) {
			//JOptionPane.showMessageDialog(null, "修改数量!");
			alterNumTF.requestFocus();
    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F6) {
			if(GoodsDataModel.checkVector()){
				JOptionPane.showMessageDialog(null,"没有交易的商品，无需交易");
			}
			else{
				checkOut();
			}
    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F7) {
			JOptionPane.showMessageDialog(null, "刷会员卡!");
    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F8) {
			JOptionPane.showMessageDialog(null, "打折!");
    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F9) {
			JOptionPane.showMessageDialog(null, "修改零售价!");
    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F11) {
			JOptionPane.showMessageDialog(null, "挂机!");
    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F2 && keyEvent.isShiftDown()) {
			JOptionPane.showMessageDialog(null, "补打!");
    	}
		else
			if(keyEvent.getKeyCode() ==  KeyEvent.VK_F2) {
				JOptionPane.showMessageDialog(null, "开钱箱!");
	    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_ESCAPE) {
			JOptionPane.showMessageDialog(null, "退出!");
    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F12 ) {
			JOptionPane.showMessageDialog(null, "银联签到!");
    	}
		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F3 && keyEvent.isShiftDown()) {
			JOptionPane.showMessageDialog(null, "联票号输入!");
    	}else
    		if(keyEvent.getKeyCode() ==  KeyEvent.VK_F3) {
    			JOptionPane.showMessageDialog(null, "全部删除!");
        	}
    
	}
}
public void actionPerformed(ActionEvent e) {
	
}
/**
 * 对话框初始化显示操作，使对话框居中显示
 * @param dlg
 */
private void showDialog(JDialog dlg){
	Dimension dlgSize = dlg.getPreferredSize();
	Dimension frmSize = getSize();
	Point loc = getLocation();
	dlg.setLocation((frmSize.width - dlgSize.width)/2 + loc.x,(frmSize.height - dlgSize.height)/2 + loc.y);
	dlg.setVisible(true);
}
/*
 * 退出系统时把当前的流水号写入文件
 */
private void writeOrderNumber(){
	try{
		DataOutputStream writeData = new DataOutputStream(new FileOutputStream(ORDERNUMBER_FILE));
		writeData.writeInt(orderNumber);
		writeData.close();
	}
	catch(IOException io){
		System.out.println(io.getMessage());
	}
}
/*
 * 结帐事务
 */
private void checkOut(){
	CheckOutDialog checkDialog = new CheckOutDialog(BaseFrame.getBaseFrame());
	showDialog(checkDialog);
	if(checkDialog.isOver){
		GoodsDataModel.clearVector();		            //清空table中的数据
		if(isAddOrderNumber){
			if(orderNumber == 999){			            //如果当前流水号为999，则使流水号置1
				orderNumber = 1;
			}
			else{
				orderNumber++;				            //流水号加1
			}
		}
		table.revalidate();
		table.repaint();
	}
}
/*
 * 清除最后一笔交易
 */
private void clearGoods(int selectRow){
	GoodsDataModel.removeLastVector(selectRow);		            //清除table中当前最后一笔交易信息
	table.revalidate();
	table.repaint();
}
/*
 * 以下方法将把要挂起的交易信息存储在文件中，其中涉及到对象存储技术
 * 但是这种方法在这里有些不合理，更好的方法是使用哈西表进行处理。
 * 我之所以没有这样处理有个人原因，^_^；
 */
private void pauseExchange(){
	
	try{
		String fileName = String.valueOf(orderNumber);
		ObjectOutputStream ooStream = new ObjectOutputStream(new FileOutputStream(fileName));
		ooStream.writeObject(GoodsDataModel.getNowVector());
		ooStream.flush();
		MyListDataModel.setListVector(orderNumber);    //把当前的交易序号添加到List数据后台
		orderNumber++;						           //商品流水号加1；
		GoodsDataModel.clearVector();
		table.revalidate();
		table.repaint();
	}
	catch(IOException io){
		System.out.println(io.getMessage());
	}
}
/*
 * 调出当前挂起交易的信息并进行相应的处理
 */
private void managerExchange(){
	ExchangeInfoDialog exDialog = new ExchangeInfoDialog(BaseFrame.getBaseFrame());
	showDialog(exDialog);
	if(exDialog.isOK){
		table.revalidate();
		table.repaint();
	}
}
/*
 * 离开系统
 */
private void exitSystem(){
	if(!GoodsDataModel.checkVector()){
		JOptionPane.showMessageDialog(this,"交易尚未完成");
	}
	else if(!MyListDataModel.checkListVector()){
		JOptionPane.showMessageDialog(this,"还有挂起的交易没有完成");
	}
	else{
		
		int result = JOptionPane.showConfirmDialog(this,"你确定离开吗？",
														   "警告",JOptionPane.OK_CANCEL_OPTION);
		if(result == JOptionPane.OK_OPTION){
			writeOrderNumber();
			System.exit(0);
		}
	}
}
}
